<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Collection;

class AdminPermission extends BaseModel
{
    use HasFactory;

    public static function booting()
    {
        static::creating(function ($model) {
            if (is_null($model->tag)) {
                $tag = getPinyinStr(self::getParent($model));
                $model->tag = $tag;
            }
        });
        static::updating(function ($model) {
            if (is_null($model->tag)) {
                $tag = getPinyinStr(self::getParent($model));
                $model->tag = $tag;
            }
        });
    }

    public static function getParent($model)
    {
        $nameArr = [];
        $nameArr[] = $model->name;
        if (!is_null($model->parent_id)) {
            $model = self::query()->find($model->parent_id);
            if (!is_null($model)) {
                $tmp = static::getParent($model);
                $nameArr = array_merge($tmp, $nameArr);
            }
        }
        return $nameArr;
    }

    public static function getPermissionTree(): array
    {
        $all = self::query()->orderBy('sort')->get();
        return self::getTree($all, null);
    }

    private static function getTree(Collection $permissions, $parentId): array
    {
        $list = [];
        foreach ($permissions->where('parent_id', $parentId) as $permission) {
            $tmp = [];
            $tmp['value'] = $permission->id;
            $tmp['label'] = $permission->name;
            $tmp['children'] = self::getTree($permissions, $permission->id);
            $list[] = $tmp;
        }
        return $list;
    }
}
